package com.xiaoxiao.source;

import org.oscim.layers.tile.MapTile;
import org.oscim.tiling.ITileDataSink;
import org.oscim.tiling.ITileDataSource;
import org.oscim.tiling.QueryResult;
import org.oscim.tiling.source.ITileDecoder;
import org.oscim.tiling.source.UrlTileSource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import static org.oscim.tiling.QueryResult.FAILED;
import static org.oscim.tiling.QueryResult.SUCCESS;

public class LocalRasterTileDataSource implements ITileDataSource {
    protected final ITileDecoder mTileDecoder;
    protected final UrlTileSource mTileSource;
    protected InputStream inputStream;

    public LocalRasterTileDataSource(UrlTileSource mTileSource, ITileDecoder mTileDecoder/*, InputStream inputStream*/) {
        this.mTileSource = mTileSource;
        this.mTileDecoder = mTileDecoder;
    }

    @Override
    public void query(MapTile tile, ITileDataSink mapDataSink) {
        QueryResult res = FAILED;
        String tileUrl = mTileSource.getTileUrl(tile).substring(7);
        try {
            inputStream = new FileInputStream(new File(tileUrl));
            if (mTileDecoder.decode(tile, mapDataSink, inputStream)) {
                res = SUCCESS;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            mapDataSink.completed(res);
        }
    }

    @Override
    public void dispose() {
        if (inputStream!=null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void cancel() {
        if (inputStream!=null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
